#!/bin/dash

#Copyright (c) 2014 Luigi Tarenga <luigi.tarenga@gmail.com>
#Distributed under the terms of a MIT license.

read last_log_applied < temp/last_log_applied
read commit_index     < temp/commit_index

while [ "$last_log_applied" -lt "$commit_index" ] ; do
   read command key value < $(echo state-machine-log/$((last_log_applied+1))/*)
   case "$command" in
   set)
      mkdir -p state-machine-data/$(dirname "$key")
      echo "$value" > state-machine-data/"$key"
   ;;
   unset)
      key="${key#/}"
      key=state-machine-data/"$key"
      rm -f "$key"
      key=$(dirname $key)
      [ -d "$key" -a "$key" != "state-machine-data" ] && rmdir "$key" 2>/dev/null
      #find state-machine-data/$(dirname "$key")/ -empty -type d -delete
      #find state-machine-data/$(dirname "$key")/ -empty -type d -exec rm -r \{\} \;
   ;;
   esac
   last_log_applied=$((last_log_applied+1))
   echo $last_log_applied > temp/last_log_applied
done
